// pages/pay/pay.js
var api = require('../../conf/api.js')
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    order: {},
    payPrice: null,
    deposit:null,
    address:null,
    coupon:null
  },
  doClickPay: function() {
    var info = {
      order_id: this.data.orderId,
      coupon_id: this.data.coupon.id,
      use_deposit: this.data.order.deposit.checked,
      address_id: this.data.address ? this.data.address.id : null,
      pay_type: this.data.order.pay_method.selected,
      real_pay: this.data.payPrice
    }
    // 将数据提交到后，支付成功，则跳转到成功页面；支付失败，提示错误信息
    console.log(info);
    var userInfo = app.globalData.userInfo;
    wx.request({
      url: api.PayNow,
      data: info,
      header: {
        Authorization: userInfo ? userInfo.token : ""
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        if (res.statusCode == 200){
          wx.navigateTo({ url: '/pages/paySuccess/paySuccess' })
        }else{
          console.log('详细错误信息',res.data)
          wx.showToast({
            title: '订单支付失败',
            icon: 'none'
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  radioChange:function(e){
    this.setData({
      ["order.pay_method.selected"]: e.detail.value
    })
  },
  useDeposit: function(e) {
    this.setData({
      ['order.deposit.checked']: e.detail.value
    })
    if (e.detail.value){
      // 去选中
      if(this.data.payPrice <= 0){
        // 如果优惠券已可以全部抵扣价格，则不需要再选择保证经
        this.setData({
          ['order.deposit.checked']: false
        })
      }else{
        // 优惠券不够，需要保证金抵扣
        if (this.data.order.deposit.balance >= this.data.payPrice){
          // 保证金 > 要支付的价格
          this.setData({
            payPrice: 0,
          })
        }else{
          // 保证金 < 要支付的价格
          this.setData({
            payPrice: this.data.payPrice - this.data.order.deposit.balance,
            deposit:this.data.order.deposit.balance,
            ['order.deposit.checked']:true
          })
        }
      }
    }else{
      // 去取消选中
      let coupon = this.data.coupon ? this.data.coupon.money : 0
      var price = this.data.order.price - coupon;
      if(price <= 0 ){
        // 原价-优惠券 <= 0
        this.setData({
          payPrice: 0
        })
      }else{
        // 原价-优惠券 > 0
        this.setData({
          payPrice: price,
          
        })
      }
    }
  },
  chooseCoupon: function(e) {
    let that = this
    var result = e.currentTarget.dataset.auction;
    console.log(result)
    wx.navigateTo({
      url: '/pages/chooseCoupon/chooseCoupon',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          let order_price = that.data.order.price
          that.setData({
            coupon: data.data,
            payPrice:that.data.order.price
          })
          console.log(data.data)
          if(data.data.money>=order_price){
            that.setData({
              payPrice: 0,
              ['order.deposit.checked']: false,
            })
            return
          }
          // 总额 - 优惠券
          var price = order_price - (data.data.money || 0);
          // 优惠后的价格 - 保证金 < 0 
          if(price-that.data.order.deposit.balance<0){
            // 保证金 - 优惠后的价格 = 剩余保证金
            let deposit = that.data.order.deposit.balance - price
            that.setData({
              payPrice: 0,
              deposit:deposit,
              ['order.deposit.checked']: true
            })
            return
          }
          // 优惠后的价格 - 保证金
          let deposit = price-that.data.order.deposit.balance
          that.setData({
            payPrice: deposit,
            ['order.deposit.checked']: true
          })
        }
      },
      success:function(res){
        res.eventChannel.emit('get_result', {data: result})
      }
    })
  },
  getPayInfo: function() {
    var userInfo = app.globalData.userInfo;
    wx.request({
      url: api.Pay + this.data.orderId + '/',
      header: {
        Authorization: userInfo ? userInfo.token : ""
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        console.log(res)
        this.setData({
          order: res.data,
          payPrice: res.data.price,
          deposit:res.data.deposit.balance
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      orderId: options.orderId
    });
    this.getPayInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getPayInfo();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})